var LBS = {
    AMapReady: false,
    heatmap: null,
};

/**
 * 引入AMap
 * @param {Object} config 引入的配置
 * @param {String} config.key  自己申请的key
 * @param {plugins} config.plugins  需要加载的插件
 */
LBS.importAMap = function (config) {
    config = config || {};
    var url = 'https://webapi.amap.com/maps?v=1.4.15';
    var key = config.key || 'e2d9c4e0aa1811c95a1621a01fae981b';
    var plugins = config.plugins || [];

    if (!this.AMapReady) {
        var script = document.createElement('script');
        script.charset = 'utf-8';
        script.src = url + '&key=' + key + '&plugin=' + plugins.join(',');
        document.head.appendChild(script);
        return new Promise(function (resolve, reject) {
            script.onload = function () {
                // AMap已经加载，现在可以使用AMap对象了
                resolve(AMap);
                LBS.AMapReady = true;
            }
            script.onerror = function (err) {
                reject(err);
                LBS.AMapReady = false;
            }
        });
    } else {
        // 这是已经存在的AMap对象
        return Promise.resolve(AMap);
    }
}

/**
 * 绘制地图标记点
 * @param {Amap} map 地图示例
 * @param {Array|Object} data 数据
 */
LBS.drawMarkers = function (map, data) {
    var markers = [];

    const createMarkerOption = d => {
        return {
            position: new AMap.LngLat(d.position[0], d.position[1]),
            offset: new AMap.Pixel(-7, -7),
            // icon: '//vdata.amap.com/icons/b18/1/2.png', // 添加 Icon 图标 URL
            icon: d.icon,
            title: d.name,
            label: d.label
        }
    }

    if (Array.isArray(data)) {
        data.forEach(item => {
            var markerOption = createMarkerOption(item);
            var marker = new AMap.Marker(markerOption);
            marker.__d__ = item;
            markers.push(marker);
            map.add(marker);
        });
    } else {
        var marker = new AMap.Marker(createMarkerOption(data));
        marker.__d__ = data;
        markers.push(marker);
        map.add(marker);
    }

    return markers;
}


/**
 * 绘制圆形标记
 * @param {Object} map 地图实例
 * @param {Array|Object} data 数据
 * @returns {Array} circleMarkers数组
 */
LBS.drawCircleMarkers = function (map, data) {
    const createCircleMarkerOption = (radius, lng, lat, color) => {
        return {
            center: new AMap.LngLat(lng, lat),
            radius: radius,
            strokeColor: color,
            strokeOpacity: 1,
            strokeStyle: "dashed",
            strokeWeight: 1,
            fillColor: color,
            fillOpacity: 0.2
        };
    };

    let circleMarkers = [];
    if (Array.isArray(data)) {
        data.forEach(item => {
            let [lng, lat] = item.position;
            let circleMarker = new AMap.Circle(
                createCircleMarkerOption(item.radius, lng, lat, item.color)
            );
            circleMarkers.push(circleMarker);
        });
    }
    else {
        let [lng, lat] = data.position;
        let circleMarker = new AMap.Circle(
            createCircleMarkerOption(data.radius, lng, lat, data.color)
        );
        circleMarkers.push(circleMarker);
    }

    map.add(circleMarkers);

    return circleMarkers;
}

/**
* 以中心创建点
* @param {*} center 地图中心点
* @param {*} num 创建的点的数量
*/
LBS.createPoints = function (center, num, accuracy = 1) {
    var data = [];
    for (var i = 0, len = num; i < len; i++) {
        data.push({
            position: [
                center[0] + (Math.random() > 0.5 ? 1 : -1) * Math.random() * accuracy,
                center[1] + (Math.random() > 0.5 ? 1 : -1) * Math.random() * accuracy
            ],
        });
    }
    return data;
}



/**
 * 在地图上显示热力图
 * @param {AMap} map 地图
 * @param {Array} data 热力图数据
 */
LBS.heatMap = function (map, data) {
    if (!isSupportCanvas()) {
        alert('热力图仅对支持canvas的浏览器适用,您所使用的浏览器不能使用热力图功能,请换个浏览器试试~')
    }
    // handle data
    var heatmapData = [];
    for (var i = 0; i < data.length; i++) {
        var item = data[i];
        heatmapData.push({
            lng: item.position[0],
            lat: item.position[1],
            count: item.count
        });
    }
    // 
    if (this.heatmap === null) {
        map.plugin(["AMap.Heatmap"], function () {
            LBS.heatmap = new AMap.Heatmap(map, {
                radius: 25, //给定半径
                opacity: [0, 0.8]
                /*,
                gradient:{
                    0.5: 'blue',
                    0.65: 'rgb(117,211,248)',
                    0.7: 'rgb(0, 255, 0)',
                    0.9: '#ffea00',
                    1.0: 'red'
                }
                 */
            });
            setDataSet();
        });
    }
    else {
        setDataSet();
    }
    function setDataSet() {
        LBS.heatmap.setDataSet({
            data: heatmapData,
            max: 100
        });
    }
    function isSupportCanvas() {
        var elem = document.createElement('canvas');
        return !!(elem.getContext && elem.getContext('2d'));
    }

    return LBS.heatmap;
}
